import tailwindcss from '@tailwindcss/vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import { fileURLToPath, URL } from 'node:url'
import AutoImport from 'unplugin-auto-import/vite'
import { ElementPlusResolver } from 'unplugin-vue-components/resolvers'
import Components from 'unplugin-vue-components/vite'
import { loadEnv, type ConfigEnv, type UserConfigExport } from 'vite'

export default (configEnv: ConfigEnv): UserConfigExport => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd())
  const { VITE_API_BASE_URL, VITE_APP_PORT,VITE_API_BASE_URL_API } = viteEnv

  return {
    plugins: [
      vue(),
      vueJsx(),
      tailwindcss(),
      AutoImport({
        resolvers: [ElementPlusResolver({ importStyle: false })],
        imports: ['vue', 'vue-router', 'pinia'],
        dts: 'src/auto-imports.d.ts',
        eslintrc: {
          enabled: false
        }
      }),
      Components({
        resolvers: [ElementPlusResolver({ importStyle: false })],
        dts: 'src/components.d.ts'
      })
    ],
    base: './',
    define: {
      __BUILD_TIME__: JSON.stringify(new Date().toISOString()),
      __BUILD_VERSION__: JSON.stringify(process.env.npm_package_version || '1.0.0')
    },
    resolve: {
      alias: {
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "@/assets/styles/variables.scss" as *;`,
          api: "modern" // 使用 Sass 现代 API，解决弃用警告
        }
      }
    },
    build: {
      target: 'es2015',
      outDir: 'dist',
      assetsDir: 'assets',
      sourcemap: configEnv.mode === 'development',
      rollupOptions: {
        output: {
          chunkFileNames: 'js/[name]-[hash].js',
          entryFileNames: 'js/[name]-[hash].js',
          assetFileNames: '[ext]/[name]-[hash].[ext]'
        }
      }
    },
    server: {
      hmr: true,
      host: '0.0.0.0',
      port: Number(VITE_APP_PORT) || 3000,
      open: false,
      cors: true,
      proxy: {
        [VITE_API_BASE_URL]: {
          target: VITE_API_BASE_URL_API,
          changeOrigin: true,
          rewrite: (path) => path.replace(VITE_API_BASE_URL, '')
        }
      }
    }
  }
}
